package com.henu.engineer.service

import com.alibaba.fastjson.JSONObject
import com.henu.engineer.dao.entity.user.Student
import com.henu.engineer.dao.entity.user.Teacher
import com.henu.engineer.dao.mapper.UserXmlMapper
import com.henu.engineer.dao.mapper.student.StudentXmlMapper
import com.henu.engineer.dao.mapper.teacher.CourseGroupMemberXmlMapper
import com.henu.engineer.dao.mapper.teacher.TeacherCourseXmlMapper
import com.henu.engineer.dao.mapper.teacher.TeacherXmlMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*
import javax.servlet.http.HttpSession
import kotlin.collections.HashMap

/**
 * @author noexcept
 * @date 2021/8/10 13:36
 *
 */
@Service
class LoginService {

    @Autowired
    lateinit var userXmlMapper: UserXmlMapper

    @Autowired
    lateinit var studentXmlMapper: StudentXmlMapper

    @Autowired
    lateinit var teacherXmlMapper: TeacherXmlMapper

    @Autowired
    lateinit var teacherCourseXmlMapper: TeacherCourseXmlMapper

    @Autowired
    lateinit var courseGroupMemberXmlMapper: CourseGroupMemberXmlMapper

    var currentUserId: String? = null

    var currentStudent: Student? = null

    var currentTeacher: Teacher? = null

    fun login(session: HttpSession, id: String, pwd: String): Pair<Boolean, HashMap<String, String>> {

        val map = HashMap<String, String>()
        val selectedPwd = userXmlMapper.selectPwd(id)
        return if (selectedPwd == null || selectedPwd.trim() != pwd.trim()) {
            map["msg"] = "账号或密码错误"
            map["token"] = ""
            map["rank"] = ""
            map["username"] = ""
            Pair(false, map)
        } else {
            currentUserId = id
            val rank = userXmlMapper.selectRank(id)
            session.setAttribute("isLogged", true)
            session.setAttribute("account", id)
            session.setAttribute("rank", rank)

            if (UserService.STUDENT == rank) {
                currentStudent = studentXmlMapper.selectStudent(id)
                map["username"] = currentStudent!!.name
            } else {
                currentTeacher = teacherXmlMapper.selectTeacher(id)
                map["username"] = currentTeacher!!.name
            }

            map["msg"] = "成功"
            map["rank"] = rank
            map["token"] = UUID.randomUUID().toString()
            Pair(true, map)
        }
    }
}